package com.hk.core.autoconfigure.zookeeper;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;

/**
 * @author Kevin
 * @date 2022-08-30 20:20:28
 */
@AutoConfiguration
@ConditionalOnClass(value = CuratorFrameworkFactory.class)
@ConditionalOnProperty(prefix = "hk.zookeeper", value = "nodes")
public class ZookeeperConfiguration {

    @Value("${hk.zookeeper.nodes:127.0.0.1:2181}")
    private String nodes;

    @Bean
    @ConditionalOnMissingBean(CuratorFramework.class)
    public CuratorFramework curatorFramework() {
        var curatorFramework = CuratorFrameworkFactory.builder()
                .connectString(nodes)
                .sessionTimeoutMs(15_000) //sessionTimout
                .connectionTimeoutMs(20_000) // connectionTimeout
                .retryPolicy(new ExponentialBackoffRetry(1000, 10)) // retry policy
                .build();
        curatorFramework.start();
        return curatorFramework;
    }
}
